// 引入user模型
const { User } = require('../model/user')
// 引入bcrypt
const bcrypt = require('bcrypt')

exports.login = async (req, res, next) => {
  try {
    let { email, password } = req.validValue
    let user = await User.findOne({ email })
    if (user) {
      // 比较密码是否一致
      let compareResult = await bcrypt.compare(password, user.password)
      if (compareResult) {
        return res.status(200).json({
          code: 200,
          msg: '登陆成功',
          authorization:{
            access_token: user.generateToken()
          }
        })
      } else {
        return res.status(200).json({
          code: 0,
          msg: '密码错误,请重新输入',
          data: user
        })
      }
    } else {
      return res.status(200).json({
        code: 0,
        msg: '该邮箱暂未注册,请注册后登录',
        data: null
      })
    }
  } catch (err) {
    res.send(err)
  }
}
